package org.jeecg.modules.purchase.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;


import org.jeecg.modules.file.entity.ProcurementFile;
import org.jeecg.modules.file.service.IProcurementFileService;
import org.jeecg.modules.message.controller.ProcurementMessageController;
import org.jeecg.modules.purchase.Vo.PurchasePlanVo;
import org.jeecg.modules.purchase.dto.PurchaseSearchRequest;
import org.jeecg.modules.purchase.entity.PurchasePlan;
import org.jeecg.modules.purchase.service.IPurchasePlanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "采购管理44")
@RestController
@RequestMapping("/procurement/purchase")
@Slf4j
public class PurchasePlanController extends JeecgController<PurchasePlan, IPurchasePlanService> {

    @Autowired
    private IPurchasePlanService purchasePlanService;

    @Autowired
    private IProcurementFileService procurementFileService;

    @Resource
    private ProcurementMessageController procurementMessageController;


    @AutoLog(value = "采购计划-分页列表查询")
    @ApiOperation(value = "采购计划-分页列表查询", notes = "采购计划-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(@RequestParam(defaultValue = "1") Integer pageNo,
                                   @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<PurchasePlan> page = new Page<>(pageNo, pageSize);
        try{
            // 创建查询条件包装器并设置按创建时间降序排序
            QueryWrapper<PurchasePlan> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("create_time");

            // 执行查询，确保只调用一次page方法
            page = purchasePlanService.page(page, queryWrapper);

            if (page.getTotal() == 0){
                return Result.OK("未查询到采购计划", page);
            }
            return Result.OK(page);
        }
        catch (Exception e){
            return Result.error("查询数据库失败：" + e.getMessage());
        }
    }

    @AutoLog(value = "采购计划-添加/草稿")
    @ApiOperation(value = "采购计划-添加/草稿", notes = "采购计划-添加/草稿")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody PurchasePlanVo purchasePlanVo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 1. 校验项目编号是否为空
        if (purchasePlanVo.getProjectNumber() == null || purchasePlanVo.getProjectNumber().trim().isEmpty()) {
            return Result.error("项目编号不能为空");
        }

        // 2. 校验项目编号是否已存在（新增时排除ID为null）
        if (purchasePlanService.checkProjectNumberExists(purchasePlanVo.getProjectNumber())) {
            return Result.error("项目编号已存在");
        }

        // 将Vo转换为实体
        PurchasePlan purchasePlan = new PurchasePlan();
        // 复制属性
        BeanUtils.copyProperties(purchasePlanVo, purchasePlan);
        // 设置创建人信息
        purchasePlan.setCreateBy(sysUser.getUsername());
        purchasePlan.setCreateTime(new Date());
        if(purchasePlanService.savePurchasePlan(purchasePlan)){
            return Result.OK("新添成功");
        }

        return Result.error("新添失败");
    }

    @AutoLog(value = "采购计划-待审核")
    @ApiOperation(value = "采购计划-待审核", notes = "采购计划-待审核")
    @PostMapping(value = "/publish")
    public Result<?> publish(@RequestParam(name = "id", required = true) String id) {
        // 获取当前登录用户
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        try {
            // 使用现有的审核方法，将采购计划状态修改为待审核（审核状态0）
            boolean success = purchasePlanService.auditPurchasePlan(id, "0", "计划待审核", sysUser.getUsername());
            if (success) {
                return Result.OK("采购计划状态修改为“待审核”成功");
            } else {
                return Result.error("采购计划状态修改为“待审核”失败");
            }
        } catch (Exception e) {
            log.error("采购计划待审核失败", e);
            return Result.error("在数据库修改失败：" + e.getMessage());
        }
    }

    @AutoLog(value = "采购计划-编辑")
    @ApiOperation(value = "采购计划-编辑", notes = "采购计划-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody PurchasePlanVo purchasePlanVo) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 校验项目编号是否为空
        if (purchasePlanVo.getProjectNumber() == null || purchasePlanVo.getProjectNumber().trim().isEmpty()) {
            return Result.error("项目编号不能为空");
        }

        // 将Vo转换为实体
        PurchasePlan purchasePlan = purchasePlanService.getById(purchasePlanVo.getId());
        if (purchasePlan == null) {
            return Result.error("采购计划不存在");
        }
        // 复制属性
        BeanUtils.copyProperties(purchasePlanVo, purchasePlan);
        // 设置更新人信息
        purchasePlan.setUpdateBy(sysUser.getUsername());
        if(purchasePlanService.updatePurchasePlan(purchasePlan)){
            return Result.OK("编辑成功");
        }

        return Result.error("编辑失败");
    }

    @AutoLog(value = "采购计划-通过id删除")
    @ApiOperation(value = "采购计划-通过id删除", notes = "采购计划-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        PurchasePlan plan = purchasePlanService.getById(id);
        if (plan == null) {
            return Result.error("采购计划不存在");
        }
        purchasePlanService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "采购计划-批量删除")
    @ApiOperation(value = "采购计划-批量删除", notes = "采购计划-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        // 校验ids是否为空
        if (ids == null || ids.trim().isEmpty()) {
            return Result.error("删除ID不能为空");
        }
        List<String> idList = Arrays.asList(ids.split(","));
        // 校验每个ID是否存在
        for (String id : idList) {
            if (purchasePlanService.getById(id) == null) {
                return Result.error("ID: " + id + " 不存在");
            }
        }
        this.purchasePlanService.removeByIds(idList);
        return Result.OK("批量删除成功!");
    }

    @AutoLog(value = "采购计划-通过id查询")
    @ApiOperation(value = "采购计划-通过id查询", notes = "采购计划-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        PurchasePlan purchasePlan = purchasePlanService.getById(id);
        if (purchasePlan == null) {
            return Result.error("未找到对应数据");
        }
        PurchasePlanVo purchasePlanVo =new PurchasePlanVo();
        // 复制属性
        BeanUtils.copyProperties(purchasePlan, purchasePlanVo);

        List<ProcurementFile> file = procurementFileService.getFilesByBiz(id,"purchase");
        purchasePlanVo.setProcurementFile(file);
        List<ProcurementFile> file2 = procurementFileService.getFilesByBiz(id,"document");
        purchasePlanVo.setDocument(file2);
        List<ProcurementFile> file3 = procurementFileService.getFilesByBiz(id,"announcement");
        purchasePlanVo.setAnnouncement(file3);
        return Result.OK(purchasePlanVo);
    }

    @AutoLog(value = "采购计划-审核")//TODO 留痕：审核意见要不要写在一个表中存起来？
    @ApiOperation(value = "采购计划-审核", notes = "采购计划-审核")
     @PostMapping(value = "/audit")
    public Result<?> audit(@RequestParam String id,
                           @RequestParam String auditStatus,
                           @RequestParam(required = false) String auditOpinion) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

//        // 校验审核状态是否合法
//        if (!"1".equals(auditStatus) && !"2".equals(auditStatus)) {
//            return Result.error("审核状态不合法，只能是1（通过）或2（驳回）");
//        }

        boolean success = purchasePlanService.auditPurchasePlan(id, auditStatus, auditOpinion,sysUser.getUsername());
        if (success) {
            return Result.OK("审核成功!");
        }
        return Result.error("审核失败!");
    }

    @AutoLog(value = "采购计划-根据审核状态获取列表")
    @ApiOperation(value = "采购计划-根据审核状态获取列表", notes = "采购计划-根据审核状态获取列表")
    @GetMapping(value = "/getListByAuditStatus")
    public Result<?> getListByAuditStatus(@RequestParam String auditStatus,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        // 校验审核状态
        if (!"0".equals(auditStatus) && !"1".equals(auditStatus) && !"2".equals(auditStatus)) {
            return Result.error("审核状态不合法，只能是0（待审核）、1（通过）、2（驳回）");
        }

        Page<PurchasePlan> page = new Page<>(pageNo, pageSize);
        PurchasePlan purchasePlan = new PurchasePlan();
        purchasePlan.setAuditStatus(auditStatus);
        IPage<PurchasePlan> pageList = purchasePlanService.queryPurchasePlanPage(page, purchasePlan);
        return Result.OK(pageList);
    }

    @AutoLog(value = "采购计划/编制-模糊查询")
    @ApiOperation(value = "采购计划/编制-模糊查询", notes = "采购计划/编制-模糊查询")
    @GetMapping(value = "/getPurchasePageBySearch")
    //    采购方案与编制模糊查询
    public Result<?> SearchPurchasePage(PurchaseSearchRequest searchRequest){
        // 如果searchRequest为null，创建默认实例
        if (searchRequest == null) {
            searchRequest = new PurchaseSearchRequest();
        }

        // 设置默认分页参数
        if (searchRequest.getPageNum() == null || searchRequest.getPageNum() <= 0) {
            searchRequest.setPageNum(1);
        }
        if (searchRequest.getPageSize() == null || searchRequest.getPageSize() <= 0) {
            searchRequest.setPageSize(10);
        }
        // 创建查询条件
        Page<PurchasePlan> page = new Page<>(searchRequest.getPageNum(), searchRequest.getPageSize());
        QueryWrapper<PurchasePlan> queryWrapper = new QueryWrapper<>();
        // 按审核状态查询
        if(searchRequest.getAuditStatus()!=null &&!searchRequest.getAuditStatus().isEmpty()){
            queryWrapper.eq("audit_status", searchRequest.getAuditStatus());
        }
        // 按所属类目查询
        if(searchRequest.getCategory()!=null && !searchRequest.getCategory().isEmpty()){
            queryWrapper.eq("category", searchRequest.getCategory());
        }
        // 按工程名称查询
        if(searchRequest.getProjectName()!=null && !searchRequest.getProjectName().isEmpty()){
            queryWrapper.like("project_name", searchRequest.getProjectName());
        }
        // 按项目编号查询
        if(searchRequest.getProjectNumber()!=null && !searchRequest.getProjectNumber().isEmpty()){
            queryWrapper.like("project_number", searchRequest.getProjectNumber());
        }
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        try {
            Page<PurchasePlan> purchasePageList = purchasePlanService.page(page, queryWrapper);
            if (page.getTotal() == 0){
                return Result.OK("未查询到采购计划", purchasePageList);
            }
            return Result.OK(purchasePageList);
        }catch (Exception e) {
            log.error("采购计划待审核失败", e);
            return Result.error("在数据库修改失败：" + e.getMessage());
        }
    }
}
